class BundleVariation < ActiveRecord::Base
  belongs_to :bundle
  has_one :trial_period, :dependent => :destroy
  has_and_belongs_to_many :application_accounts
  
  validate :bundle_must_exist

  # validates_associated :trial_period
  validates_presence_of :frequency, :price
  validates_uniqueness_of :frequency, :price, :scope => [:bundle_id], :message => "must be unique within a bundle"
  validates_numericality_of  :price
  
  accepts_nested_attributes_for :trial_period, :reject_if => proc { |attributes| attributes['period'].blank? }
  
  
  #----- Act as FINITE STATE MACHINE -------------
    acts_as_state_machine :initial => :active, :column => :status
    
    state :inactive, :column => :status
    state :active, :column => :status
    
    event :activate do
       transitions :from => :inactive, :to => :active
    end

    event :deactivate do
      transitions :from => :active, :to => :inactive
    end
    
    # reference of statuses for this model
    def self.statuses
      [RefActionStatus::ACTIVE, RefActionStatus::INACTIVE]
    end
  #-----------------------------------------------
  
  protected
  def self.frequency
    # %w(daily monthly yearly)
    return [RefDate::WEEKLY, RefDate::MONTHLY, RefDate::QUARTERLY, RefDate::YEARLY].collect
  end
  
  private
  def bundle_must_exist
    errors.add(:bundle_id, "must point to an existing Bundle") if bundle_id && bundle.nil?
  end
  
end
